<?php


namespace App\Web\Model\RabbitMQ;

use App\Web\Model\Model;
use EchoPHP\Facades\Log;
use EchoPHP\Rabbitmq\Query\QueueProducer;

/**
 * 通知消息生产者
 * Class NoticeProducer
 * @package App\Web\Model\RabbitMQ
 */
class NoticeProducer extends Model {

    //新增客户
    const MODULE_CUSTOMER_ADD = 'addCustomer';
    const MODULE_CUSTOMER_EDIT = 'editCustomer';
    const MODULE_INTERVIEW_APPLY = 'createInterviewRoomApply';
    const MODULE_INTERVIEW_CHECK = 'createInterviewRoomCheck';

    private $producer;
    private $queueName;

    public function __construct() {
        $businessConfig = config('rabbitmq.businesses.noticehandler');
        if (is_null($businessConfig)) {
            throw  new \Exception('生产者队列未定义');
        }
        $this->producer = new QueueProducer($businessConfig['exchange']);
        $this->queueName = $businessConfig['queuename'];
    }

    /**
     * 添加异步通知记录
     * @param $module   模块名称
     * @param array $params 异步通知所需要的参数
     * @param bool $ignoreHandler 默认忽略不发送给操作人
     * @throws \AMQPChannelException
     * @throws \AMQPConnectionException
     * @throws \AMQPExchangeException
     * @throws \AMQPQueueException
     */
    public function add($module, array $params, bool $ignoreHandler = true) {
        $params = array_merge($params, [
            'action' => $module,
            'time' => time(),
            'ignorehandler' => $ignoreHandler ? 1 : 0
        ]);

        $queueName = $this->queueName;
        $messages = ['message' => $params, 'routekey' => $queueName];
        $this->producer->produce([$messages], $queueName, true, [$this, 'dealAck'], [$this, 'dealNack']);
    }

    /**
     * @param $delivery_tag
     * @param array $messageInfo
     * @return bool
     */
    public function dealAck($delivery_tag, $messageInfo) {
        return true;
    }

    /**
     * @param $delivery_tag
     * @param array $messageInfo
     * @return bool
     */
    public function dealNack($delivery_tag, $messageInfo) {
        Log::error('通知消息异步创建失败', ['delivery_tag' => $delivery_tag, 'message' => $messageInfo]);
        return true;
    }
}